﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using DaphneTranslatorWPF.Mvvm;
using FolderBrowser;
using System.IO;
using System.Windows;
using DaphneTranslator.BusinessLogic;

namespace DaphneTranslatorWPF.ViewModel
{
    /// <summary>
    /// View model for path selection user control
    /// </summary>
    public class PathSelectionViewModel: INotifyPropertyChanged
    {
        public PathSelectionViewModel()
        {
            RootPath = string.Empty;
            SelectPathCommand = new DelegateCommand<object>(SelectPathExecute);
            EnterRelativePath = false;
        }

        /// <summary>
        /// Binding of root path
        /// </summary>
        public string RootPath
        { get; set; }

        public bool EnterRelativePath
        { get; set; }

        public string EnteredPath
        { get; set; }

        public Window ParentWindow
        { get; set; }

        public DelegateCommand<object> SelectPathCommand
        { get; set; }

        protected void SelectPathExecute(object o)
        {
            FolderBrowserDialog browserDialog = new FolderBrowserDialog();
            Window parentWindow = ParentWindow ?? Application.Current.MainWindow;
            browserDialog.Owner = parentWindow;

            string sPath = Directory.GetCurrentDirectory();
            if (string.IsNullOrWhiteSpace(RootPath) == false)
                sPath = RootPath;
            BrowserViewModel viewModel = new BrowserViewModel();
            viewModel.SelectedFolder = sPath;
            browserDialog.DataContext = viewModel;

            if (browserDialog.ShowDialog().Value == true)
            {
                string sEnteredPath = viewModel.SelectedFolder;

                if (EnterRelativePath == true)
                {
                    try
                    {
                        sEnteredPath = DirectoryHelper.RelativePath(sEnteredPath, RootPath);
                    }
                    catch
                    {
                        MessageBox.Show("The selected path is not relative to the root path.");
                        return;
                    }
                }

                EnteredPath = sEnteredPath;
                OnPropertyChanged("EnteredPath");
            }           
        }

        public void OnPropertyChanged(string sProperty)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(sProperty));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
